//
//  EditUserInfoViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/5/7.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
class EditUserInfoViewController: BaseViewController {

    @IBOutlet var userHeaderVIew: UIImageView!
    
    @IBOutlet var phoneLabel: UILabel!
    
    @IBOutlet var nameLabel: UILabel!
    
    @IBOutlet var ageTF: UITextField!
    
    
    @IBOutlet var sexBtn: UIButton!
    
    @IBOutlet var workYearsTF: UITextField!
    
    
    @IBOutlet var goodAtAreaTF: UITextField!
    
    
    @IBOutlet var workTypeLabel: UILabel!
    
    @IBOutlet var roleLabel: UILabel!
    
    @IBOutlet var storeNameLabel: UILabel!
    
    @IBOutlet var saveBtn: UIButton!
    
    var  headerImageUrl = ""
    var  sexId = "1"  //1 男 2 女 
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        userHeaderVIew.roundCorner(radius: userHeaderVIew.frame.height/2)
        requestGetUserInfo()
        
    }
    
    func updateVcEvents(model:UserdetailModel) -> Void {
        
        //赋值
        sexId = model.sex
        headerImageUrl = model.head_url        
        
        //更新页面
        userHeaderVIew.sd_setImage(with: (NSURL(string:(model.head_url))! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
         phoneLabel.text = model.account
         nameLabel.text = model.name
         ageTF.text = model.age
         workYearsTF.text = model.work_time
         goodAtAreaTF.text = model.skill
         workTypeLabel.text = model.work_name
         roleLabel.text = model.role_id
         storeNameLabel.text = model.store_name
        if model.sex == "1" {
            sexBtn.setTitle("男", for: .normal)
        }else {
            sexBtn.setTitle("女", for: .normal)
        }
        
        if model.role_id == "1" {//老板
            roleLabel.text = "老板"
        }else if model.role_id == "2" {//店长
            roleLabel.text = "店长"
        }else if model.role_id == "3"{//员工
            roleLabel.text = "员工"
        }
    }
    

    @IBAction func saveBtnPress(_ sender: UIButton) {
        
        if goodAtAreaTF.text! == "" || ageTF.text! == "" || workYearsTF.text! == ""{
            MBProgressHUD.alertShow(in: self.view, message: "请填写完整再保存", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
            
            return
        }
        requestEditUserInfo(age: self.ageTF.text!, workTime: self.workYearsTF.text!, headUrl: self.headerImageUrl, goodAtArea: goodAtAreaTF.text!, sex:self.sexId)
        
    }
    
    
    @IBAction func sexBtnPress(_ sender: UIButton) {
        BRStringPickerView.showStringPicker(withTitle: "员工性别", dataSource: ["男","女"], defaultSelValue: "男", isAutoSelect: true) { (str,index) in
            self.sexBtn.setTitle(str as? String, for: .normal)
            self.sexId = String(index + 1)
        }
    }
    
    
    
    @IBAction func chooseImageBtnPress(_ sender: UIButton) {
    
        alertChooseTakePhotoOrAlbum(typeName: "用户头像")
    }

    
    //选择照片或者拍照
    func alertChooseTakePhotoOrAlbum(typeName:String) -> Void {
        let alertController = UIAlertController(title: "上传图片", message: typeName,
                                                preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let takephtotAction = UIAlertAction(title: "拍照", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerCamera, in: self, scale: 1)
        })
        let albumAction = UIAlertAction(title: "相册", style: .default, handler:{
            action in
            let imagePicker = LDImagePicker.sharedInstance()
            imagePicker?.delegate = self as LDImagePickerDelegate
            imagePicker?.show(with: ImagePickerPhoto, in: self, scale: 1)
            
        })
        alertController.addAction(cancelAction)
        alertController.addAction(takephtotAction)
        alertController.addAction(albumAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    //获取用户信息
    func requestGetUserInfo() -> Void {
        
        Alamofire.request(getUserInfoUrl, method:.post, parameters:["uid":UserModel.shareUser.data?.uid ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<UserdetailModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if (basemodel.data != nil){
                            self.updateVcEvents(model:basemodel.data!)
                        }
                    
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //修改用户信息
    func requestEditUserInfo(age:String,workTime:String,headUrl:String,goodAtArea:String,sex:String) -> Void {
        let param =
            ["age":age,
             "work_time":workTime,
             "skill":goodAtArea,
             "head_url":headUrl,
             "sex":sex,
             "sid":UserModel.shareUser.data?.storeId ?? String(),
             "uid":UserModel.shareUser.data?.uid ?? String(),
             ] as [String : Any]
        
        Alamofire.request(editUserInfoUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                        hud?.mode = MBProgressHUDMode.text
                        hud?.labelText = "保存成功"
                        hud?.show(animated: true, whileExecuting: {                        Thread.sleep(forTimeInterval: 0.8)
                        }, completionBlock: {                    self.navigationController?.popViewController(animated: true)
                        })
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }

    
    
    //上传头像
    func requestUploadCoverPhoto(imageName:String,imageData:Data) -> Void {
        
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "filed", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadHePhotoUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = BaseResponseOfModel<PhotoModel>()
                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                        switch basemodel.status! {
                        case true:
                            print("上传成功")
                            if (basemodel.data != nil){
                                
                                self.userHeaderVIew.sd_setImage(with: (NSURL(string:(basemodel.data?.url)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
                                self.headerImageUrl = (basemodel.data?.url)!
                            }
                            
                            
                        case false:
                             MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension EditUserInfoViewController: LDImagePickerDelegate {
    
    func imagePickerDidCancel(_ imagePicker: LDImagePicker!) {
        
    }
    
    func imagePicker(_ imagePicker: LDImagePicker!, didFinished editedImage: UIImage!) {
        let imageData = UIImageJPEGRepresentation(editedImage, 0.00001)
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let str = formatter.string(from:NSDate() as Date) + ".jpg"
        requestUploadCoverPhoto(imageName: str, imageData: imageData!)
    }
        
}

